package com.hotel.wallet.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotel.common.config.RabbitKeyConfig;
import com.hotel.common.param.GrowthAdd;
import com.hotel.common.param.MqMsg;

import com.hotel.user.entity.UserGrowthLog;
import com.hotel.user.entity.UserLevel;
import com.hotel.wallet.mapper.UserGrowthLogMapper;
import com.hotel.wallet.mapper.UserLevelMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class GrowthRabbitListener {

    @Autowired
    private UserGrowthLogMapper userGrowthLogMapper;


    @Autowired
    private UserLevelMapper userLevelMapper;

    @RabbitListener(queues = RabbitKeyConfig.Q_USER_GROWTH)
    public void growthListener(MqMsg msg){

        System.out.println("msg = " + msg);

        if (msg.getType() == 4) {

            // 获得需要增加的积分
            GrowthAdd growthAdd = (GrowthAdd) msg.getMsg();

            // 1.根据uid查询该用户积分项,如果为null说明该用户没用登陆或注册过,不允许加分
            QueryWrapper<UserLevel> userLevelQueryWrapper = new QueryWrapper<>();
            userLevelQueryWrapper.eq("user_id", growthAdd.getUid());
            List<UserLevel> levelList = userLevelMapper.selectList(userLevelQueryWrapper);
            UserLevel level = levelList.get(0);

            if (level != null) {
                // 添加用户积分
                level.setGrowths(level.getGrowths() + growthAdd.getGrowth());

                // 等级改变
                if (level.getGrowths()<100){
                    level.setLevel(1);
                    level.setName("练气");
                }else if (level.getGrowths()<1000){
                    level.setLevel(2);
                    level.setName("筑基");
                }else if (level.getGrowths()<10000) {
                    level.setLevel(2);
                    level.setName("金丹");
                }
                // 更新表中数据
                userLevelMapper.updateById(level);
            }

            // 2.添加日志
            UserGrowthLog growthLog = new UserGrowthLog();
            growthLog.setCtime(new Date())
                    .setUserId(growthAdd.getUid())
                    .setType(growthAdd.getType())
                    .setInfo(growthAdd.getType() + "积分增加" + growthAdd.getGrowth());
            userGrowthLogMapper.insert(growthLog);

        }

    }

}
